//
// Created by sai on 2019/2/21.
//
#include "Linklist.h"
#include <stdio.h>
#include <stdlib.h>

bool IsEmpty(List L) {
    return L->Next == NULL;
}

bool IsLast(Position P, List L) {
    return P->Next == NULL;
}

List MakeEmpty(List L) {
    List head;
//    if (L->Next == NULL)
//        return L;
    head = malloc(sizeof(struct Node));
    head->Next = NULL;
    return head;
}

Position Find(ElementType X, List L) {
    Position P;
    P = L->Next;
    while (P != NULL && P->Element != X)
        P = P->Next;
    return P;
}

void Delete(ElementType X, List L) {
    Position P, TmpCell;
    P = FindPrevious(X, L);
    if (!IsLast(P, L)) {
        TmpCell = P->Next;
        P->Next = P->Next->Next;
        free(TmpCell);
    }
}

Position FindPrevious(ElementType X, List L) {
    Position P;
    P = L;
    while (P->Next != NULL && P->Next->Element != X)
        P = P->Next;
    return P;
}

void Insert(ElementType X, List L, Position P) {
    Position TmpCell;
    TmpCell = malloc(sizeof(struct Node));
    if (TmpCell == NULL)
        printf("out of range");
    TmpCell->Element = X;
    TmpCell->Next = P->Next;
    P->Next = TmpCell;
}

void Append(List L, ElementType X) {
    Position P;
    P = L;
    while (P->Next != NULL)
        P = P->Next;
    Insert(X, L, P);
}


ElementType Retrieve(Position P) {
    return P->Element;
}

void DeleteList(List L) {
    Position P, TmpP;
    P = L->Next;
    L->Next = NULL;
    while (P != NULL) {
        TmpP = P->Next;
        free(P);
        P = TmpP;
    }
    free(L);
}

void PrintList(List L) {
    Position P;
    P = L->Next;
    while (P != NULL) {
        printf(" %d", P->Element);
        P = P->Next;
    }
}

Position Header(List L) {
    return L;
}

Position First(List L) {
    return L->Next;
}

Position Advance(Position P) {
    return P = P->Next;
}

